import React, { FC, ReactElement, useMemo } from 'react';
import { SideSheet } from '@douyinfe/semi-ui';
import { useMatches } from 'react-router-dom';
import { routes } from '@/router';
import { AdminLayout, MessageList } from '@/components';
import { useLoginUser } from '@/store';
import { useMessageList, useTheme, useLoginCheck } from '@/hooks';
import type { MenuRouteObject } from '@/types/router';

const HomePage: FC = (): ReactElement => {
  const {
    messageList,
    messageListVisible,
    handleCheckMessageList,
    handleCloseMessageList,
  } = useMessageList();
  const routeMatch = useMatches();
  const loginUser = useLoginUser();
  const { theme, toggleTheme } = useTheme();
  useLoginCheck();

  const pageRoutes: MenuRouteObject[] = useMemo(() => {
    return getPageRoutes(routes);

    function getPageRoutes(routes: MenuRouteObject[]) {
      return routes.reduce<MenuRouteObject[]>((res, item) => {
        if (item.path === '*' || item.path.startsWith('common')) {
          return res;
        }
        res.push(item);

        if (item?.children?.length) {
          item.children = getPageRoutes(item.children);
        }

        return res;
      }, []);
    }
  }, []);

  const flattenPageRoutes: MenuRouteObject[] = useMemo(() => {
    return doFlattenPageRoutes(pageRoutes);

    function doFlattenPageRoutes(routes: MenuRouteObject[], initialValue: MenuRouteObject[] = []) {
      return routes.reduce((res, item) => {
        if (item.path === '*') {
          return res;
        }
        res.push(item);

        if (item?.children?.length) {
          doFlattenPageRoutes(item.children, res);
        }
        
        return res;
      }, initialValue);
    }
  }, [pageRoutes]);

  const itemKeys = useMemo(() => {
    if (!routeMatch?.length) return [];
    return routeMatch.map((item) => item.pathname) as string[];
  }, [routeMatch]);

  const breadcurmbList = useMemo(() => {
    return routeMatch.map(
      item => flattenPageRoutes.find(r => r.fullpath === item.pathname)?.title
    );
  }, [routeMatch, flattenPageRoutes]);

  return (
    <>
      <AdminLayout
        showSider
        pageRoutes={pageRoutes}
        itemKeys={itemKeys}
        showMessageBtn
        theme={theme}
        loginUser={loginUser}
        toggleTheme={toggleTheme}
        onMessageBtnClick={handleCheckMessageList}
        breadcurmbList={breadcurmbList}
      />
      <SideSheet
        title="查看消息列表"
        visible={messageListVisible}
        closeOnEsc
        onCancel={handleCloseMessageList}
        // maskClosable={false}
      >
        {messageListVisible && <MessageList list={messageList} />}
      </SideSheet>
    </>
  );
}

export default HomePage;